﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using EstimateTracker.Domain.Entities;

namespace EstimateTracker.DataAccess.Repositories
{
    public class TaskRepository : ITaskRepository
    {
        private readonly IPersistenceManager _persistenceManager;

        public TaskRepository(IPersistenceManager persistenceManager)
        {
            if (persistenceManager == null) throw new ArgumentNullException("persistenceManager");
            _persistenceManager = persistenceManager;
        }

        public void Save(Task activity)
        {
            using (var scope = new TransactionScope())
            {
                _persistenceManager.Persist(activity);
                scope.Complete();
            }
        }

        public IEnumerable<Task> FindByActivityId(int id)
        {
            return _persistenceManager.GetNamedQuery<Task>("FindByActivityId").SetParameter("Id", id).GetResultList();
        }

        public IEnumerable<object[]> FindActualsForDay(DateTime date)
        {
            return _persistenceManager.GetNamedQuery<object[]>("FindActualsForDay")
                                      .SetParameter("TodaysDateStart", date.Date)
                                      .SetParameter("TodaysDateEnd",date.Date.AddDays(1).AddSeconds(-1))
                                      .GetResultList().ToList();
        } 

        public double FindActualsForTask(int id)
        {
            return _persistenceManager.GetNamedQuery<double>("FindActualsForTask")
                        .SetParameter("Id", id)
                        .GetResultList()
                        .FirstOrDefault();
        }
    }
}